import React, { useState } from "react"
import { Image, ITouchEvent, Text, View } from "@tarojs/components"
import clsx from "clsx"
import Taro from "@tarojs/taro"
import { ContentNoteAttachmentType } from "@/types/enum"
import { navigation } from "@/utils/router"
import { pageMapperCommunity } from "@/constants/pageMap"
import styles from "./index.module.scss"
import { noteLikeSwitch } from "@/apis/yikao-community"
import { requestIsFullfilled } from "@/utils/request"
import { ImageProps } from "@tarojs/components/types/Image"

type INoteItem = {
  image?: string
  title?: React.ReactNode
  avatar?: string
  name?: React.ReactNode
  likes?: number
  liked?: boolean
  /** 类型 */
  fileType?: ContentNoteAttachmentType
  /** 是否显示视频标识 */
  videoFlag?: boolean
  /** 是否显示操作标识 */
  actionFlag?: boolean
  /** 笔记内容
   * @description 当笔记无标题时, 显示此字段
   */
  content?: string
  /** 是否显示审核标识
   * @default false
   */
  auditFlag?: boolean
  /** 笔记审核状态信息
   * @description 当`auditFlag`为`true`时需要传此参数
   */
  auditStatusJson?: IUserInfo["auditStatusJson"] | null
} & PrimaryKey<number>
type IProps = {
  /**
   * 当前组件是否处于skyline渲染引擎下
   * @default false
   */
  skyline?: boolean
  /** @default true */
  forceSkyline?: boolean
  className?: string
  noteItem: INoteItem
  /** @default true */
  clickToNavigation?: boolean
  /** 点赞成功回调 */
  onLike?: (noteItem: INoteItem, meta: IApiRelative.INoteLikeSwitch.IResData) => void
  onClick?: (noteItem: INoteItem) => void
  onAction?: (noteItem: INoteItem) => void
}
/**
 * @component 笔记卡片
 */
export default function GpNoteItem({
  skyline = false,
  forceSkyline = true,
  className,
  noteItem,
  onClick,
  onLike,
  clickToNavigation = true,
  onAction
}: IProps) {
  const defAspect = 338 / 450
  const [center, setCenter] = useState(false)
  const isVideo = noteItem.fileType === ContentNoteAttachmentType.Video
  function handleClick() {
    if (clickToNavigation) {
      if (noteItem.fileType === ContentNoteAttachmentType.Image) {
        navigation(pageMapperCommunity.NoteDetail, { id: noteItem.id })
      } else if (isVideo) {
        navigation(pageMapperCommunity.VideoNoteDetail, { id: noteItem.id })
      }
    } else {
      onClick && onClick(noteItem)
    }
  }
  function handleLike(ev: ITouchEvent) {
    ev.stopPropagation()
    noteLikeSwitch({ id: noteItem.id }).then(res => {
      if (requestIsFullfilled(res)) {
        const { isLike, likeCount } = res.data.data
        Taro.showToast({
          title: !isLike ? "已取消点赞" : "点赞成功",
          icon: "none"
        })
        onLike && onLike(noteItem, { isLike, likeCount })
      }
    })
  }
  function handleAction(ev: ITouchEvent) {
    ev.stopPropagation()
    onAction && onAction(noteItem)
  }
  function handleImageLoad(ev: { detail: ImageProps.onLoadEventDetail }) {
    const { width, height } = ev.detail
    const aspect = Number(width) / Number(height)
    setCenter(aspect > defAspect)
  }
  function getShowTitle() {
    if (noteItem.title) return noteItem.title
    if (noteItem.content) {
      return noteItem.content.split(/\r?\n+/).join("")
    }
    return null
  }
  function renderWebViewView() {
    return (
      <View className={clsx(styles.noteItem, className)} onClick={handleClick}>
        <View
          style={{
            width: "100%",
            position: "relative"
          }}
        >
          <Image
            src={noteItem.image as string}
            className={styles.image}
            onLoad={handleImageLoad}
            mode={center ? "center" : "scaleToFill"}
          />
          {renderAuditFlag()}
        </View>
        <View className={styles.info}>
          <View className={clsx("ellipse_2", styles.title)}>{getShowTitle()}</View>
          <View className={styles.desc}>
            <Image
              className={styles.avatar}
              src={(noteItem.avatar as string) || process.env.__DEF_AVATAR__}
            />
            <View className={styles.name}>{noteItem.name}</View>
            {renderLikes()}
            {noteItem.likes}
          </View>
        </View>
        {renderVideoFlag()}
        {renderActionFlag()}
      </View>
    )
  }
  function renderSkylineView() {
    return (
      <View
        style={{
          width: "100%",
          boxSizing: "border-box",
          backgroundColor: "#ffffff",
          borderRadius: 8,
          overflow: "hidden",
          position: "relative"
        }}
        className={className}
        onClick={handleClick}
      >
        {/* 图片地址不存在默认显示固定高度元素 */}
        {noteItem.image ? (
          <View
            style={{
              width: "100%",
              position: "relative"
            }}
          >
            <Image
              src={noteItem.image as string}
              mode="widthFix"
              style={{
                width: "100%",
                boxSizing: "border-box",
                display: "block",
                objectFit: "cover",
                maxHeight: 225
              }}
            />
            {renderAuditFlag()}
          </View>
        ) : (
          <View
            style={{
              width: 168,
              height: 225,
              boxSizing: "border-box"
            }}
          >
            {renderAuditFlag()}
          </View>
        )}
        <View
          style={{
            paddingLeft: 8,
            paddingRight: 8,
            paddingTop: 12,
            paddingBottom: 12,
            boxSizing: "border-box"
          }}
        >
          {skyline ? (
            <Text
              style={{
                lineHeight: "18px",
                fontSize: 14,
                color: "#333333",
                fontWeight: 500
              }}
              overflow="ellipsis"
              maxLines={2}
            >
              {getShowTitle()}
            </Text>
          ) : (
            <View className={clsx("ellipse_2", styles.title)}>{getShowTitle()}</View>
          )}
          <View
            style={{
              display: "flex",
              marginTop: 12,
              color: "#999999",
              fontSize: 12,
              flexDirection: "row",
              alignItems: "center",
              boxSizing: "border-box"
            }}
          >
            <Image
              style={{
                width: 15,
                height: 15,
                boxSizing: "border-box",
                marginRight: 4,
                flex: "none",
                borderRadius: "100%",
                objectFit: "cover"
              }}
              src={(noteItem.avatar as string) || process.env.__DEF_AVATAR__}
            />
            {skyline ? (
              <Text
                style={{
                  flex: 1,
                  width: 0
                }}
                overflow="ellipsis"
              >
                {noteItem.name}
              </Text>
            ) : (
              <View className={styles.name}>{noteItem.name}</View>
            )}
            {renderLikes()}
            {noteItem.likes}
          </View>
        </View>
        {renderVideoFlag()}
        {renderActionFlag()}
      </View>
    )
  }
  function renderLikes() {
    return (
      <Image
        src={
          noteItem.liked ? "/images/yikao-community/like.png" : "/images/yikao-community/unlike.png"
        }
        onClick={handleLike}
        style={{
          flex: "none",
          marginLeft: 8,
          marginRight: 2,
          width: 12,
          height: 12,
          pointerEvents: "auto"
        }}
      />
    )
  }
  function renderVideoFlag() {
    if (isVideo && noteItem.videoFlag) {
      return (
        <Image
          src="https://csstatic.91goodschool.com/UpFiles/gp/1000/202404/17/165847530773.png"
          style={{
            position: "absolute",
            right: 8,
            top: 8,
            width: 24,
            height: 24,
            objectFit: "cover"
          }}
        />
      )
    }
  }
  function renderActionFlag() {
    if (noteItem.actionFlag) {
      return (
        <View
          style={{
            width: 40,
            height: 30,
            position: "absolute",
            right: 0,
            top: 0,
            boxSizing: "border-box",
            display: "flex",
            flexDirection: "row",
            justifyContent: "center",
            alignItems: "center"
          }}
          onClick={handleAction}
        >
          <Image
            src={
              noteItem.image
                ? "https://csstatic.91goodschool.com/UpFiles/gp/1000/202404/15/142158823742.png"
                : "https://csstatic.91goodschool.com/UpFiles/gp/1000/202404/15/142158823593.png"
            }
            style={{
              height: 6,
              objectFit: "cover"
            }}
            mode="heightFix"
          />
        </View>
      )
    }
  }
  function renderAuditFlag() {
    const { auditFlag, auditStatusJson } = noteItem
    // 坤鹏: auditStatus >= 2 才显示黄色
    if (!auditFlag || auditStatusJson?.value === 0 || auditStatusJson?.value === 1) return
    let style = {} as React.CSSProperties
    if (auditStatusJson?.value === 4) {
      const weiguiStyle = {
        background: "#ff5000cc"
      }
      style = {
        ...style,
        ...weiguiStyle
      }
    } else if (auditStatusJson?.value === 2) {
      const shenhezhongStyle = {
        background: "#ff8615cc"
      }
      style = {
        ...style,
        ...shenhezhongStyle
      }
    }
    return (
      <View
        style={{
          left: "50%",
          top: "50%",
          transform: "translate(-50%, -50%)",
          color: "#fff",
          fontSize: 12,
          height: 28,
          borderRadius: 16,
          paddingLeft: 8,
          paddingRight: 8,
          position: "absolute",
          display: "flex",
          flexDirection: "row",
          alignItems: "center",
          width: "fit-content",
          ...style
        }}
      >
        {auditStatusJson?.value === 4 && (
          <Image
            src="/images/yikao-community/info.png"
            style={{
              width: 14,
              height: 14,
              boxSizing: "border-box",
              flex: "none"
            }}
          />
        )}
        <View
          style={{
            flex: "none"
          }}
        >
          {auditStatusJson?.name}
        </View>
      </View>
    )
  }
  if (skyline || forceSkyline) {
    return renderSkylineView()
  }
  return renderWebViewView()
}
